import { makeObservable, observable, action, computed } from 'mobx'
import { BaseStore } from '../BaseStore'
import type { Theme, Language } from './index.d'

export class UIStore extends BaseStore {
  theme: Theme = 'light'
  language: Language = 'en'
  sidebarOpen = true
  modalStack: string[] = []

  constructor() {
    super()
    makeObservable(this, {
      theme: observable,
      language: observable,
      sidebarOpen: observable,
      modalStack: observable,
      toggleTheme: action,
      setLanguage: action,
      toggleSidebar: action,
      openModal: action,
      closeModal: action,
      isModalOpen: computed,
    })

    // 从 localStorage 恢复设置
    this.initializeFromStorage()
  }

  private initializeFromStorage = (): void => {
    const savedTheme = localStorage.getItem('theme') as Theme
    const savedLanguage = localStorage.getItem('language') as Language

    if (savedTheme) this.theme = savedTheme
    if (savedLanguage) this.language = savedLanguage
  }

  // Actions
  toggleTheme = (): void => {
    this.theme = this.theme === 'light' ? 'dark' : 'light'
    localStorage.setItem('theme', this.theme)
  }

  setLanguage = (language: Language): void => {
    this.language = language
    localStorage.setItem('language', language)
  }

  toggleSidebar = (): void => {
    this.sidebarOpen = !this.sidebarOpen
  }

  openModal = (modalId: string): void => {
    if (!this.modalStack.includes(modalId)) {
      this.modalStack.push(modalId)
    }
  }

  closeModal = (modalId: string): void => {
    this.modalStack = this.modalStack.filter(id => id !== modalId)
  }

  closeTopModal = (): void => {
    this.modalStack.pop()
  }

  // Computed values
  get isModalOpen(): boolean {
    return this.modalStack.length > 0
  }

  get currentModal(): string | undefined {
    return this.modalStack[this.modalStack.length - 1]
  }
}